/**
 * Created by lili on 2017/8/4.
 */
;(function (window,doc,undef) {
    "use strict";
    var topics = {},//对象数组  {"topic1":[{token:xxx,func:func},{}],"topic2":[{},{}]}
        subUid = -1,
        pubsub = {};

    //发布主题
    pubsub.publish = function(topic,args){
        if(!topics[topic]){
            return false;
        }


        //保证异步订阅
        setTimeout(function(){
            var subscribes = topics[topic],
                len = subscribes?subscribes.length:0;
            while (len--){
                subscribes[len].func(topics,args);
            }
        },0);

        return true;
    };

    //订阅主题
    pubsub.subscribe = function(topic,func){


        if(!topics[topic]){
            topics[topic] = [];
        }

        //标识唯一主题
        var token = (++subUid).toString();

        topics[topic].push({
            token:token,
            func:func
        });

        return token;
    };

    pubsub.unsubscribe = function(token){
        for(var m in topics){
            if(topics[m]){
                for(var i=0,j=topics[m].length;i<j;i++){
                    if(topics[m][i].token === token){
                        topics[m].splice(i,1);
                        return token;
                    }
                }
            }
        }
        return false;
    };

    var getPubSub = function () {
        return pubsub;
    };

    window.pubsub = getPubSub();


}(this,this.document));





